package com.cnswhy.cloud.server.app.controller.notify;

import com.alibaba.fastjson.JSONObject;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.CnswhyUtil;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.common.entity.enumeration.PayType;
import com.cnswhy.cloud.server.core.appservice.AppChargeMoneyService;
import com.cnswhy.cloud.server.core.appservice.AppSpellOrderService;
import com.cnswhy.cloud.server.core.channel.service.SandeService;
import com.cnswhy.cloud.server.core.entity.BuyBackOrder;
import com.cnswhy.cloud.server.core.entity.ChargeMoney;
import com.cnswhy.cloud.server.core.entity.ShopOrder;
import com.cnswhy.cloud.server.core.entity.SpellOrder;
import com.cnswhy.cloud.server.core.service.ChargeMoneyService;
import com.cnswhy.cloud.server.core.service.shop.ShopOrderService;
import com.cnswhy.cloud.server.core.service.spell.BuyBackOrderService;
import com.cnswhy.cloud.server.core.service.spell.SpellOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;

/**
 * 描述: 阿里支付回调
 * 版权: Copyright (c) 2019
 * 公司: 小鹿科技
 * 作者: 张润泽
 * 版本: 1.0
 * 创建日期: 2019年11月19日
 * 创建时间: 下午5:26:23
 */
@Controller
@RequestMapping("/sandePayNotify")
@Slf4j
public class SandePayNotify extends BaseController {


    @Autowired
    private RedisService redisService;


    @Autowired
    private ShopOrderService shopOrderService;


    @Autowired
    private ChargeMoneyService chargeMoneyService;

    @Autowired
    private BuyBackOrderService buyBackOrderService;

    @Autowired
    private SpellOrderService spellOrderService;
    @Autowired
    AppChargeMoneyService appChargeMoneyService;
    @Autowired
    AppSpellOrderService appSpellOrderService;
    @Autowired
    SandeService sandeService;

    @SuppressWarnings("rawtypes")
    @PostMapping("/notify")
    public void sandePayNotify(HttpServletRequest request, HttpServletResponse response) {
        log.error("============================杉德回调开始");
        response.setCharacterEncoding("UTF-8");
        //设置字符流编码，而且还会添加content-Type响应头，这个头通知浏览器用utf-8解码。
        response.setContentType("text/html;charset=utf-8");


        try {
            // 返回success
            PrintWriter out = response.getWriter();
            out.print("success");
            out.flush();
            out.close();
            String body = new String(request.getParameter("body").getBytes("ISO-8859-1"), "UTF-8");
            log.info("收到杉德支付回调，内容：" + body);

            JSONObject jsonObjectbody = JSONObject.parseObject(body);

            // 商户订单号
            String outTradeNo = jsonObjectbody.get("orderCode").toString();
            // 交易流水
            String tradeNo = jsonObjectbody.get("tradeNo").toString();
            // 交易状态
            String tradeStatus = jsonObjectbody.get("orderStatus").toString();
            // 交易金额
            String totalAmount = jsonObjectbody.get("totalAmount").toString();

            String orderType = outTradeNo.substring(0, 2);
            BigDecimal orderPrice = BigDecimal.ZERO;
            if ("SH".equals(orderType)) {
                ShopOrder queryByOrderNo = shopOrderService.queryByPayOrderNo(outTradeNo);
                orderPrice = queryByOrderNo.getOrderPrice();
            } else if ("BU".equals(orderType)) {
                BuyBackOrder queryByOrderNo = buyBackOrderService.getOne(Wraps.<BuyBackOrder>lbQ().eq(BuyBackOrder::getReturnOrderNum, outTradeNo));
                orderPrice = queryByOrderNo.getOrderPrice();
            } else if ("SP".equals(orderType)) {
                SpellOrder order = spellOrderService.getOne(Wraps.<SpellOrder>lbQ().eq(SpellOrder::getPayOrderNum, outTradeNo));
                orderPrice = order.getOrderPrice();
            } else {
                ChargeMoney queryByOrderNo = chargeMoneyService.getOne(Wraps.<ChargeMoney>lbQ().eq(ChargeMoney::getOrderNum, outTradeNo));
                orderPrice = CnswhyUtil.getMoney(queryByOrderNo.getChargeMoney());
            }

            String result = sandeService.orderQuery(outTradeNo);
            // 调用SDK验证签名
            JSONObject jsonObject = JSONObject.parseObject(result);

            String status = jsonObject.get("orderStatus").toString();
            // 订单金额一致，判断订单状态
            if (orderPrice.compareTo(new BigDecimal(totalAmount)) == 0) {
                // 支付成功
                if ("00".equals(tradeStatus) && "00".equals(status)) {
                    appSpellOrderService.saveOrderNotify(outTradeNo, tradeNo);
                }
                // 失败
                else {
                    log.info("【注意】名品名店订单号为" + outTradeNo + "的杉德支付回调状态为失败，错误码：" + tradeStatus);
                }
            } else {
                log.info("【注意】名品名店订单号为" + outTradeNo + "的杉德支付回调订单金额与订单金额不一致，将丢弃此回调信息");
            }


        } catch (Exception e) {
            log.error("杉德支付回调异常：", e);
        }
    }

    /**
     * 描述：防止回调重复，校验redis中是否已经存在此订单
     * 作者：张润泽
     * 时间：2019年3月19日 上午10:48:42
     *
     * @param orderNo
     * @return true 不存在此订单  false 已存在此订单
     */
    private boolean validateOrderNo(String orderNo) {
        String order = (String) redisService.get(orderNo);
        if (StringUtils.isBlank(order)) {
            // 将订单号放入redis中60分钟
            redisService.set(orderNo, "60");
            redisService.expire(orderNo, 600L);
            return true;
        }
        return false;
    }
}
